package com.wcl.demo.ui.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.wcl.demo.R;
import com.wcl.demo.model.entity.Mp3Info;
import com.wcl.demo.ui.adapter.MusicAdapter;
import com.wcl.demo.view.CustomToast;
import com.wcl.demo.view.MusicLoader;
import com.wcl.demo.view.NatureService;
import com.wcl.demo.view.NatureService.NatureBinder;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by dllo on 15/11/21.
 */
public class HomeMusicActivity extends BaseActivity{


    @Bind(R.id.pbDuration)
    SeekBar pbDuration;
    private List<MusicLoader.MusicInfo> musicList;
    private int currentMusic;
    private int currentPosition;
    private int currentMax;

    @Bind(R.id.btnStartStop)
    Button btnStartStop;
    @Bind(R.id.btnNext)
    Button btnNext;
    @Bind(R.id.btnDetail)
    Button btnDetail;
    @Bind(R.id.tvCurrentMusic)
    TextView tvCurrentMusic;
    @Bind(R.id.lvSongs)
    ListView lvSongs;

    private ProgressReceiver progressReceiver;
    private NatureBinder natureBinder;
    private MusicAdapter adapter;

    private ServiceConnection serviceConnection =new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            natureBinder = (NatureBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private void connectToNatureService(){
        Intent intent = new Intent(this, NatureService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_musichome;
    }

    @Override
    protected void initView() {
        adapter=new MusicAdapter();
        MusicLoader musicLoader=MusicLoader.instance(getContentResolver());
        musicList=musicLoader.getMusicList();
        lvSongs.setAdapter(adapter);
        adapter.addData(musicList);
        lvSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentMusic = position;
                natureBinder.startPlay(currentMusic,0);
                if(natureBinder.isPlaying()){
                    btnStartStop.setBackgroundResource(R.mipmap.pause);
                }
            }
        });
        connectToNatureService();

    }

    @Override
    protected void initData() {
        pbDuration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    natureBinder.changeProgress(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }
    class ProgressReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(NatureService.ACTION_UPDATE_PROGRESS.equals(action)){
                int progress = intent.getIntExtra(NatureService.ACTION_UPDATE_PROGRESS, 0);
                if(progress > 0){
                    currentPosition = progress; // Remember the current position
                    pbDuration.setProgress(progress / 1000);
                }
            }else if(NatureService.ACTION_UPDATE_CURRENT_MUSIC.equals(action)){
                //Retrive the current music and get the title to show on top of the screen.
                currentMusic = intent.getIntExtra(NatureService.ACTION_UPDATE_CURRENT_MUSIC, 0);
                tvCurrentMusic.setText(musicList.get(currentMusic).getTitle());
            }else if(NatureService.ACTION_UPDATE_DURATION.equals(action)){
                //Receive the duration and show under the progress bar
                //Why do this ? because from the ContentResolver, the duration is zero.
                currentMax = intent.getIntExtra(NatureService.ACTION_UPDATE_DURATION, 0);
                int max = currentMax / 1000;
               // Log.v(TAG, "[Main ProgressReciver] Receive duration : " + max);
                pbDuration.setMax(currentMax / 1000);
            }
        }

    }
    @OnClick(R.id.btnStartStop)void btnStartStop(){
        play(currentMusic, R.id.btnStartStop);
    }
    @OnClick(R.id.btnNext)void btnNext(){
        natureBinder.toNext();
    }
    @OnClick(R.id.btnDetail)void btnDetail(){
        CustomToast.toastShow(this, "你说你跳不跳");
    }
    private void play(int position, int resId){
        if(natureBinder.isPlaying()){
            natureBinder.stopPlay();
            btnStartStop.setBackgroundResource(R.mipmap.play);
        }else{
            natureBinder.startPlay(position,currentPosition);
            btnStartStop.setBackgroundResource(R.mipmap.pause);
        }
    }

    public void onResume(){
      //  Log.v(TAG, "OnResume register Progress Receiver");
        super.onResume();
        registerReceiver();
        if(natureBinder != null){
            if(natureBinder.isPlaying()){
                btnStartStop.setBackgroundResource(R.mipmap.pause);
            }else{
                btnStartStop.setBackgroundResource(R.mipmap.play);
            }
            natureBinder.notifyActivity();
        }
    }

    public void onPause(){
      //  Log.v(TAG, "OnPause unregister Progress Receiver");
        super.onPause();
        unregisterReceiver(progressReceiver);
    }

    public void onStop(){
    //    Log.v(TAG, "OnStop");
        super.onStop();
    }

    public void onDestroy(){
     //   Log.v(TAG, "OnDestroy");
        super.onDestroy();
        if(natureBinder != null){
            unbindService(serviceConnection);
        }
    }
    private void registerReceiver(){
        progressReceiver = new ProgressReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(NatureService.ACTION_UPDATE_PROGRESS);
        intentFilter.addAction(NatureService.ACTION_UPDATE_DURATION);
        intentFilter.addAction(NatureService.ACTION_UPDATE_CURRENT_MUSIC);
        registerReceiver(progressReceiver, intentFilter);
    }
}
